package com.digitalchina.dcn.dcss.web.enums;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Administrator on 2016/7/14 0014.
 */
public class StringEnumTypeHandler<E extends Enum<E> & StringEnum<E>> extends
        BaseTypeHandler<StringEnum> {

    private Class<StringEnum> type;

    public StringEnumTypeHandler(Class<StringEnum> type) {
        if (type == null)
            throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    private StringEnum convert(String value) {
        StringEnum[] objs = type.getEnumConstants();
        for (StringEnum em : objs) {
            if (em.getStringValue().equals(value)) {
                return em;
            }
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, StringEnum stringEnum, JdbcType jdbcType) throws SQLException {
        // baseTypeHandler已经帮我们做了parameter的null判断
        preparedStatement.setString(i, stringEnum.getStringValue());
    }

    @Override
    public StringEnum getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return convert(resultSet.getString(s));
    }

    @Override
    public StringEnum getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return convert(resultSet.getString(i));
    }

    @Override
    public StringEnum getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return convert(callableStatement.getString(i));
    }
}
